import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/pages/order/order_add/model/model_add_order.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/widgets/appbar/common_app_bar.dart';
import 'package:flutter_yn_goods/widgets/button/common_button.dart';
import 'package:get/get.dart';

import 'order_add_logic.dart';

class OrderAddPage extends StatelessWidget {
  OrderAddPage({Key? key}) : super(key: key);

  final OrderAddLogic logic = Get.put(OrderAddLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommonAppBar(
          title: LocaleKeys.input_order.tr,
        ),
        body: SafeArea(child: GetBuilder<OrderAddLogic>(
          builder: (c) {
            return Column(
              children: [
                Container(
                  margin: EdgeInsets.only(left: 16.w),
                  alignment: Alignment.centerLeft,
                  height: 40.w,
                  child: Text(
                    '${LocaleKeys.agent_code.tr}：${AppUserManager().user.value?.id}',
                    style: TextStyle(
                      color: AppColor.color282828,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                Expanded(
                  child: SingleChildScrollView(
                      padding: EdgeInsets.all(16.w).copyWith(top: 0),
                      child: Column(
                        children: [
                          for (int i = 0; i < logic.orderGoodsRx.length; i++)
                            _buildItem(logic.orderGoodsRx[i], i),
                          // ...logic.orderGoodsRx.map((item) {
                          //   return _buildItem(item);
                          // }),
                          24.verticalSpaceFromWidth,
                          CommonButton(
                            title: LocaleKeys.add_order.tr,
                            enable: false,
                            width: 150.w,
                            alwaysCanClick: true,
                            onClick: () {
                              clog('message');
                              ModelAddOrder addOrder = ModelAddOrder();
                              logic.addOrderListener(addOrder);
                              logic.orderGoodsRx.add(addOrder);
                              // logic.orderGoodsRx.add(ModelAddOrder(
                              //     numController:
                              //         TextEditingController(text: '1')));
                              logic.update();
                            },
                          ),
                          Padding(
                            padding: EdgeInsets.all(16.w),
                            child: CommonButton.expend(
                              title: LocaleKeys.submit.tr,
                              onClick: () {
                                logic.addOrder();
                                // logic.getLeaderUserInfo();
                              },
                            ),
                          )
                        ],
                      )),
                ),

              ],
            );
          },
        )));
  }

  Widget _buildItem(ModelAddOrder addOrder, int index) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              // margin: EdgeInsets.only(left: 16.w),
              alignment: Alignment.centerLeft,
              height: 40.w,
              child: Text(
                '${LocaleKeys.order.tr}${index + 1}',
                style: TextStyle(
                  color: AppColor.color282828,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
           Visibility(
             visible: index > 0,
             child:  GestureDetector(
             onTap: () {
               addOrder.productFocusNode?.dispose();
               addOrder.memberFocusNode?.dispose();
               addOrder.numFocusNode?.dispose();
               addOrder.numController?.dispose();
               logic.orderGoodsRx.remove(addOrder);
               logic.update();
             },
             behavior: HitTestBehavior.opaque,
             child: Container(
               width: 44.w,
               height: 44.w,
               alignment: Alignment.center,
               child: Icon(
                 Icons.delete_forever,
                 weight: 16.w,
                 color: AppColor.color282828,
               ),
             ),
           ),)
          ],
        ),

        _buildInputItem(
            LocaleKeys.customer_code.tr, LocaleKeys.enter_customer_code.tr,
            focusNode: addOrder.memberFocusNode!, onChanged: (text) {
          addOrder.uid = text;
        }),
        if (addOrder.userInfo != null) ...[
          _buildTextItem(LocaleKeys.customer_name_label.tr,
              addOrder.userInfo?.nickname ?? ''),
          _buildTextItem(LocaleKeys.customer_phone_label.tr,
              addOrder.userInfo?.phone ?? ''),
          _buildTextItem(LocaleKeys.customer_address_label.tr,
              addOrder.userInfo?.address ?? ''),
        ],
        _buildInputItem(LocaleKeys.customer_product_code.tr,
            LocaleKeys.enter_product_code.tr,
            focusNode: addOrder.productFocusNode!, onChanged: (text) {
          addOrder.pid = text;
        }),
        if (addOrder.orderGoods != null) ...[
          _buildNumItem(LocaleKeys.order_count.tr, addOrder),
          _buildTextItem(
              LocaleKeys.product_name.tr, addOrder.orderGoods?.storeName ?? ''),
          _buildTextItem(LocaleKeys.total_amount.tr,
              addOrder.orderGoods?.totalPrice ?? ''),
          _buildTextItem(LocaleKeys.company_receivable_amount.tr,
              addOrder.orderGoods?.companyPrice ?? ''),
        ],
      ],
    );
  }

  Widget _buildNumItem(String title, ModelAddOrder addOrder) {
    return _buildBaseItem(
      title,
      Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          GestureDetector(
            onTap: () {
              int currentValue =
                  int.tryParse(addOrder.numController?.text ?? '1') ?? 1;
              if (currentValue > 1) {
                addOrder.numController?.text = (currentValue - 1).toString();
                logic.getLeaderProduct(addOrder);
              }
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              width: 44.w,
              height: 44.w,
              alignment: Alignment.center,
              child: Icon(
                Icons.remove_circle_outline,
                weight: 16.w,
                color: AppColor.color282828,
              ),
            ),
          ),
          SizedBox(
            width: 40.w,
            child: TextField(
              controller: addOrder.numController,
              // 使用controller管理TextField
              textAlign: TextAlign.center,
              style: TextStyle(
                color: AppColor.color282828,
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
              ),
              keyboardType: TextInputType.number,
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
              maxLength: 2,
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.all(0),
                border: noneBorder,
                focusedBorder: noneBorder,
                enabledBorder: noneBorder,
                hintText: '',
                counterText: "",
                isDense: true,
              ),
              onChanged: (text) {
                // 更新数量的逻辑
              },
              onSubmitted: (text) {
                if (text.isEmpty) {
                  addOrder.numController?.text = '1';
                }
                logic.getLeaderProduct(addOrder);
              },
            ),
          ),
          GestureDetector(
            onTap: () {
              int currentValue =
                  int.tryParse(addOrder.numController?.text ?? '1') ?? 1;
              addOrder.numController?.text = (currentValue + 1).toString();
              logic.getLeaderProduct(addOrder);
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              width: 44.w,
              height: 44.w,
              alignment: Alignment.center,
              child: Icon(
                Icons.add_circle_outline,
                weight: 16.w,
                color: AppColor.color282828,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTextItem(String title, String info) {
    return _buildBaseItem(
        title,
        Text(
          info,
          textAlign: TextAlign.end,
          style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: AppColor.color282828),
        ));
  }

  Widget _buildInputItem(String title, String hintText,
      {required FocusNode focusNode, required Function(String) onChanged}) {
    return _buildBaseItem(
      title,
      TextField(
        focusNode: focusNode,
        // controller: controller,
        // obscureText: obscureText,
        textAlign: TextAlign.end,
        style: TextStyle(
            color: AppColor.color282828,
            fontSize: 14.sp,
            fontWeight: FontWeight.w500),
        // maxLength: maxLength,
        textInputAction: TextInputAction.done,
        maxLength: 32,
        keyboardType: const TextInputType.numberWithOptions(),
        inputFormatters: [FilteringTextInputFormatter.digitsOnly],

        decoration: InputDecoration(
          contentPadding: const EdgeInsets.all(0),
          border: noneBorder,
          focusedBorder: noneBorder,
          enabledBorder: noneBorder,
          hintStyle: TextStyle(
              color: AppColor.color999999,
              fontSize: 14.sp,
              fontWeight: FontWeight.w400),
          hintText: hintText,
          counterText: "",
          isDense: true,
        ),
        onChanged: (text) {
          onChanged.call(text);
        },
        // onSubmitted: (text) {
        //   onSubmitted.call(text);
        //   // inputText = text;
        //   // clog('addOrder.uid   ${addOrder.uid}');
        // },
      ),
    );
  }

  Widget _buildBaseItem(String title, Widget rightWidget) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.w),
      padding: EdgeInsets.symmetric(horizontal: 12.w),
      decoration: BoxDecoration(
          border: Border.all(
            width: 1,
            color: AppColor.color999999,
          ),
          borderRadius: BorderRadius.circular(12.w)),
      height: 44.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
                color: AppColor.color282828.withOpacity(0.8)),
          ).marginOnly(right: 12.w),
          Expanded(child: rightWidget),
        ],
      ),
    );
  }

  InputBorder get noneBorder {
    return const OutlineInputBorder(
      borderSide: BorderSide.none,
    );
  }
}
